
package com.kugou.game.sdk.ui.fragment;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnRequestValidateCodeV3Listener;
import com.kugou.game.sdk.interfaces.OnResetPasswordListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

@SuppressLint("NewApi")
/**
 * 
 * 描述:安全手机找回密码
 *
 * @author wcj
 * @since  2015年8月14日 下午2:32:37
 */
public class GetBackPasswdByPhoneFragment extends BaseSDKWorkerFragment {

    private static final int MSG_REFRESH_VIEW = 10000;

    private static final int MSG_START_TIMER = 10001;

    private static final int MSG_REQUEST_VALIDATE_CODE = 10002;

    private static final int MSG_REQUEST_VALIDATE_CODE_SUCCESS = 10003;

    private static final int MSG_REQUEST_VALIDATE_CODE_FAILE = 10004;

    private static final int MSG_RESET_PASSWORD = 10005;

    private static final int MSG_RESET_PASSWORD_SUCCESS = 10006;

    private static final int MSG_RESET_PASSWORD_FAILE = 10007;

    private static final int MSG_SHOW_LOADING_VIEW = 10008;

    private static final int MSG_HIDE_LOADING_VIEW = 10009;

    private String mKugouUserName, mPhoneNum, mPhoneNumWithStar;

    private EditText mValidateCodeEditText, mPasswdEditText;

    private Button mRequestValidateCodeBtn;

    private TextView mRequestedValidateCodeTips, mUserNameTextView, mPhoneTextView;

    private int mTimer;

    private String mUnixtTime, mToken;

    ScrollView mScrollView;

    LoadingView mLoadingView;

    public static GetBackPasswdByPhoneFragment createFragment() {
        GetBackPasswdByPhoneFragment fragment = new GetBackPasswdByPhoneFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int layoutId = Rx.layout.kg_fragment_get_back_password_by_phone;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_fragment_get_back_password_by_phone_land;
        }
        View view = inflater.inflate(layoutId, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mUserNameTextView = (TextView) view.findViewById(Rx.id.kg_tv_account);

        mPhoneTextView = (TextView) view.findViewById(Rx.id.kg_tv_phone);

        mValidateCodeEditText = (EditText) view.findViewById(Rx.id.kg_et_input_validate_code);
        mPasswdEditText = (EditText) view.findViewById(Rx.id.kg_et_input_new_psd);

        mRequestValidateCodeBtn = (Button) view.findViewById(Rx.id.kg_btn_request_validate_code);
        mRequestValidateCodeBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                sendEmptyBackgroundMessage(MSG_REQUEST_VALIDATE_CODE);
            }
        });

        mRequestedValidateCodeTips = (TextView) view.findViewById(Rx.id.kg_tv_validate_code_tips);

        Button submitBtn = (Button) view.findViewById(Rx.id.kg_summit_get_password_back_button);
        submitBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (checkCodeAndPasswd()) {
                    sendEmptyBackgroundMessage(MSG_RESET_PASSWORD);
                }
            }
        });

        mScrollView = (ScrollView) view.findViewById(Rx.id.kg_layout_scrollview);

        mLoadingView = (LoadingView) view.findViewById(Rx.id.kg_loading);
    }

    private boolean checkCodeAndPasswd() {
        String smsCheckCode = mValidateCodeEditText.getText().toString().trim();
        String newPsd = mPasswdEditText.getText().toString().trim();

        if (TextUtils.isEmpty(smsCheckCode)) {
            showToast("验证码不能为空");
            return false;
        } else if (TextUtils.isEmpty(newPsd)) {
            showToast("新密码不能为空");
            return false;
        }

        return true;
    }

    private void showConfimDialog() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(getActivity());
        dialog.setMessage("密码修改成功！");
        dialog.setSuccessLogoVisibility(View.VISIBLE);
        dialog.setTextGravity(Gravity.CENTER);
        dialog.setCancelBtnVisibility(false);
        dialog.setOKBtnText("知道了");
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getActivity().finish();
            }
        });
        dialog.show();
    }

    private void requestValidateCodeSuccess() {
        mRequestedValidateCodeTips.setVisibility(View.VISIBLE);
        mTimer = 60;
        sendEmptyUiMessage(MSG_START_TIMER);
        mRequestValidateCodeBtn.setClickable(false);
    }

    public void setData(String userName, String phone) {
        mKugouUserName = userName;
        mPhoneNum = phone;
        mPhoneNumWithStar = AppUtil.getPhoneWithStar(phone);
        sendEmptyUiMessage(MSG_REFRESH_VIEW);
    }

    @SuppressLint("NewApi")
    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }

        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_REFRESH_VIEW:
                mUserNameTextView.setText("酷狗账号：" + mKugouUserName);
                mPhoneTextView.setText(Html.fromHtml("<font color=#ff333333>安全手机：</font>"
                        + "<font color=#249EF4>" + mPhoneNumWithStar + "</font>"));
                break;

            case MSG_START_TIMER:
                mRequestValidateCodeBtn.setText(mTimer + "s");
                if (mTimer == 60) {
                    mRequestedValidateCodeTips.setText(Html
                            .fromHtml("<font color=#ff333333>已发送验证码到你的安全手机：</font>"
                                    + "<font color=#249EF4>" + mPhoneNumWithStar + "</font>"));
                    sendEmptyUiMessageDelayed(MSG_START_TIMER, 1000);
                } else if (mTimer <= 0) {
                    mRequestValidateCodeBtn.setText("获取验证码");
                    mRequestValidateCodeBtn.setClickable(true);
                } else {
                    sendEmptyUiMessageDelayed(MSG_START_TIMER, 1000);
                }

                mTimer--;
                break;

            case MSG_REQUEST_VALIDATE_CODE_SUCCESS:
                requestValidateCodeSuccess();
                Bundle bundle = msg.getData();
                if (bundle != null && bundle.containsKey("unixtime") && bundle.containsKey("token")) {
                    mUnixtTime = bundle.getString("unixtime");
                    if (mUnixtTime == null) {
                        mUnixtTime = "";
                    }
                    mToken = bundle.getString("token");
                    if (mToken == null) {
                        mToken = "";
                    }
                }
                break;

            case MSG_REQUEST_VALIDATE_CODE_FAILE:
                showToast("发送验证码失败：" + msg.obj);
                break;

            case MSG_RESET_PASSWORD_SUCCESS:// 重置密码成功
                // 通知登录页面显示修改后的信息
                Intent intent = new Intent(SDKActions.ACTION_GET_NEW_PASSWORD);
                intent.putExtra(BaseCommonTitleFragmentActivity.USER_NICKNAME_KEY, mKugouUserName);
                intent.putExtra(BaseCommonTitleFragmentActivity.USER_PASSWORD_KEY, mPasswdEditText
                        .getText().toString().trim());
                getActivity().sendBroadcast(intent);

                showConfimDialog();
                break;
            case MSG_RESET_PASSWORD_FAILE:// 重置密码失败
                String prompt = (String) msg.obj;
                if (!TextUtils.isEmpty(prompt)) {
                    showToast(prompt);
                } else {
                    showToast("请求网络失败");
                }

                break;

            case MSG_SHOW_LOADING_VIEW:
                hideSoftInput(getActivity());
                mScrollView.setVisibility(View.GONE);
                mLoadingView.setVisibility(View.VISIBLE);
                break;
            case MSG_HIDE_LOADING_VIEW:
                mScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                break;

            default:
                break;
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);

        final Message message = Message.obtain();

        switch (msg.what) {
            case MSG_REQUEST_VALIDATE_CODE:// 请求验证码
                sendEmptyUiMessage(MSG_SHOW_LOADING_VIEW);
                UserManager.getInstance().requestValidateCodeV3(mKugouUserName, 3, mPhoneNum,
                        new OnRequestValidateCodeV3Listener() {

                            @Override
                            public void onSuccess(String unixtime, String token) {
                                message.what = MSG_REQUEST_VALIDATE_CODE_SUCCESS;
                                Bundle bundle = new Bundle();
                                bundle.putString("unixtime", unixtime);
                                bundle.putString("token", token);
                                message.setData(bundle);
                            }

                            @Override
                            public void onFailed(String errorMsg, String errorCode) {
                                message.what = MSG_REQUEST_VALIDATE_CODE_FAILE;
                                message.obj = errorMsg;
                            }

                        });
                sendEmptyUiMessage(MSG_HIDE_LOADING_VIEW);
                sendUiMessage(message);
                break;

            case MSG_RESET_PASSWORD:
                sendEmptyUiMessage(MSG_SHOW_LOADING_VIEW);
                String smsCheckCode = mValidateCodeEditText.getText().toString().trim();
                String newPsd = mPasswdEditText.getText().toString().trim();
                UserManager.getInstance().resetPasswordV3(mPhoneNum, mKugouUserName, newPsd,
                        smsCheckCode, mUnixtTime, mToken, new OnResetPasswordListener() {
                            @Override
                            public void onSuccess() {
                                message.what = MSG_RESET_PASSWORD_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_RESET_PASSWORD_FAILE;
                                message.obj = errorMsg;

                            }
                        });
                sendEmptyUiMessage(MSG_HIDE_LOADING_VIEW);
                sendUiMessage(message);
                break;

            default:
                break;
        }
    }
}
